﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Caliburn.Core.Metadata;
using Caliburn.PresentationFramework.ApplicationModel;
using Caliburn.PresentationFramework;
using XWord.Fundamental.Domain;
using Microsoft.Practices.ServiceLocation;
using System.Threading;
using XWord.Fundamental.Domain.Model;
using XWord.WPF.ApplicationFramework;
using Luna.WPF.ApplicationFramework;
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows;
using XWord.WPF.ApplicationFramework.Threads;
using XWord.GUI.Presenters.Interface;
using XWord.Fundamental.Domain.Services;
using XWord.Common;

namespace XWord.GUI.Presenters.Fundamental
{
    [Singleton("EtymaLibraryExplorerPresenter", typeof(IEtymaLibraryExplorerPresenter))]
    public class EtymaLibraryExplorerPresenter : DockingPresenter, IEtymaLibraryMasterScreen, IEtymaLibraryExplorerPresenter
    {
        
        private readonly IServiceLocator _serviceLocator;
        public EtymaLibraryExplorerPresenter(IServiceLocator entityFactory)
        {
            this.DisplayName = "词根";
            _serviceLocator = entityFactory;
            Application.Current.Exit += new ExitEventHandler(Current_Exit);
        }

        void Current_Exit(object sender, ExitEventArgs e)
        {
            if (AllEtymaLibraryList.Count > 0)
                BinaryFormatterHelper.Serialize(BinaryFiles.AllEtymaLibraryList, AllEtymaLibraryList.ToArray());
        }

        protected override void OnInitialize()
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback((object obj) =>
            {
                AllEtymaLibraryList = BinaryFormatterHelper.Deserialize<IList<EtymaLibrary>>(BinaryFiles.AllEtymaLibraryList).ToObservableCollection();
            }));

            base.OnInitialize();
        }

        #region EtymaList

        public IObservableCollection<EtymaMessage> _suffixEtymaList;
        public IObservableCollection<EtymaMessage> SuffixEtymaList
        {
            get { return _suffixEtymaList ?? (_suffixEtymaList = new BindableCollection<EtymaMessage>()); }
            set
            {
                _suffixEtymaList = value;
                NotifyOfPropertyChange("SuffixEtymaList");
            }
        }

        public IObservableCollection<EtymaMessage> _prefixEtymaList;
        public IObservableCollection<EtymaMessage> PrefixEtymaList
        {
            get { return _prefixEtymaList ?? (_prefixEtymaList = new BindableCollection<EtymaMessage>()); }
            set
            {
                _prefixEtymaList = value;
                NotifyOfPropertyChange("PrefixEtymaList");
            }
        }

        public IObservableCollection<EtymaMessage> _bindableprefixEtymaList;
        public IObservableCollection<EtymaMessage> BindablePrefixEtymaList
        {
            get { return _bindableprefixEtymaList ?? (_bindableprefixEtymaList = new BindableCollection<EtymaMessage>()); }
            set
            {
                _bindableprefixEtymaList = value;
                NotifyOfPropertyChange("BindablePrefixEtymaList");
            }
        }

        public IObservableCollection<EtymaMessage> _etymaMessageList;
        public IObservableCollection<EtymaMessage> EtymaMessageList
        {
            get { return _etymaMessageList ?? (_etymaMessageList = new BindableCollection<EtymaMessage>()); }
            set
            {
                _etymaMessageList = value;
                NotifyOfPropertyChange("EtymaMessageList");
            }
        }

        public IObservableCollection<EtymaLibrary> _alletymaLibraryList;
        public IObservableCollection<EtymaLibrary> AllEtymaLibraryList
        {
            get { return _alletymaLibraryList ?? (_etymaLibraryList = new BindableCollection<EtymaLibrary>()); }
            set
            {
                _alletymaLibraryList = value;
                NotifyOfPropertyChange("AllEtymaLibraryList");
            }
        }

        public IObservableCollection<EtymaLibrary> _etymaLibraryList;
        public IObservableCollection<EtymaLibrary> EtymaLibraryList
        {
            get { return _etymaLibraryList ?? (_etymaLibraryList = new BindableCollection<EtymaLibrary>()); }
            set
            {
                _etymaLibraryList = value;
                NotifyOfPropertyChange("EtymaLibraryList");
            }
        }

        #endregion

        private EtymaLibrary _selectedItem;
        public EtymaLibrary SelectedItem
        {
            get { return _selectedItem; }
            set
            {
                _selectedItem = value;
                NotifyOfPropertyChange("SelectedItem");
            }
        }

        #region Edit

        public void OpenNewDialog()
        {
            OpenDialog(false);
        }

        public void OpenEditDialog()
        {
            OpenDialog(true);
        }

        private void OpenDialog(bool IsEdit)
        {
            var presenter = ServiceLocator.Current.GetInstance<EtymaLibraryEditPresenter>();
            presenter.Entity = this.SelectedItem;
            _windowManager
               .ShowDialog(presenter, null, ExecuteShutdownModel);
        }

        public void Delete()
        {
            EtymaLibraryList.Remove(SelectedItem);
        }

        #endregion

        public void Search(string text)
        {
            this.EtymaLibraryList = this.AllEtymaLibraryList.
                   Where(e =>EtymaUtil.ParseText(e.Name).Any(m => m.Name.StartsWith(text))).Take(20).ToObservableCollection();
        }

        public const string WordinfoEngine = "http://www.wordinfo.info/words/index/info/view_unit/{0}";

        public void OpenEtymaDetail(EtymaLibrary etyma)
        {
            var webBrowserPresenter = _serviceLocator.GetInstance<WebBrowserPresenter>();
            webBrowserPresenter.Show(etyma.Name, new Uri(string.Format(WordinfoEngine,etyma.WordIndex)));
        }

        private bool _isOpen;
        public bool IsOpen
        {
            get { return _isOpen; }
            set
            {
                _isOpen = value;
                NotifyOfPropertyChange("IsOpen");
            }
        }

        private string _etymaTip;
        public string EtymaTip
        {
            get { return _etymaTip; }
            set
            {
                _etymaTip = value;
                NotifyOfPropertyChange("EtymaTip");
            }
        }

        public void AddEtyma(IDataObject obj)
        {
            EtymaTip = "正在添加词根";
            IsOpen = true;

            var str = Convert.ToString(obj.GetData(DataFormats.UnicodeText));
            if (string.IsNullOrEmpty(str))
            {
                IsOpen = false;
                return;
            }
            if (AllEtymaLibraryList.Any(e => e.Name.Trim() == str.ToLower().Trim()))
            {
                CloseTip(string.Format("{0}已经在列表中", str));
            }
            else
            {
                InternalAdd(str);
                CloseTip(string.Format("{0}添加成功", str));
            }
        }

        private void CloseTip(string tip)
        {
            EtymaTip = tip;
            GapDispatcherTimer.BeginInvoke(1, () =>
            {
                IsOpen = false;
            });
        }

        private void InternalAdd(string str)
        {
            EtymaLibrary el = new EtymaLibrary();
            el.Id = Guid.NewGuid();
            el.Name = str.ToLower().Trim();
            el.Comment = string.Empty;
            AllEtymaLibraryList.Add(el);
            EtymaLibraryList.Insert(0, el);
        }
    }
}
